const router = require("koa-router")();
const DB = require("../../module/db");
const sd = require("silly-datetime");
const crypto = require("crypto");
const fs = require("fs");

router.get("/", async (ctx) => {
    ctx.body = "后台用户首页";

}).post("/addUser", async (ctx) => {
    let data = ctx.request.body;
    let data2 = await DB.find('user', {"email": data.email});
    if (data2.toString().length === 0) {
        let createTime = new Date();
        let salt = createTime + getRandomSalt();
        let list = {
            "email": data.email,
            "password": cryptPwd(data.password, salt),
            "phoneNumber": "",
            "username": "Novice",
            "sex": "",
            "occupation": "",
            "company": "",
            "about": "",
            "salt": salt
        }
        let result = await DB.insert('user', list);
        let time = sd.format(new Date(), 'YYYY-MM-DD HH:mm');
        try {
            if (result.result.ok) {
                // console.log(result.ops[0]._id)
                ctx.body = {
                    "message": "注册成功",
                    "userId": result.ops[0]._id,
                    "username": "Novice"
                };
                console.log(time + "：添加用户成功" + ctx.request.body["email"]);
            } else {
                ctx.body = "注册失败";
            }
        } catch (e) {
            ctx.body = e;
            console.log(time + "：" + e);
        }
    } else
        ctx.body = "该邮箱已被注册";


}).post("/findUser", async (ctx) => {
    // let data = ctx.request.body;
    // let data2 = await DB.find('user', {"email": data.email});
    // let time = sd.format(new Date(), 'YYYY-MM-DD HH:mm');
    // if (data2.toString().length > 0){
    //     let salt = data2[0]["salt"];
    //     let password = cryptPwd(data.password, salt);
    //     if (password === data2[0]["password"]) {
    //         ctx.body = {
    //             "userId": data2[0]["_id"],
    //             "userName": data2[0]["userName"]
    //         };
    //         console.log(time + "：查找用户成功" + data2[0]["_id"]);
    //     } else
    //         ctx.body = "密码错误";
    // } else
    //     ctx.body = "该邮箱未注册";
    let data = ctx.request.body;
    console.log(data)
    let data2 = await DB.find('user', {"username": data.username});
    let time = sd.format(new Date(), 'YYYY-MM-DD HH:mm');
    if (data2.toString().length > 0){
        ctx.body = data2[0]
        console.log(time + "：查找用户成功" + data2[0]["_id"]);
    } else
        ctx.body = "该用户未注册";

}).post("/findUser2", async (ctx) => {
    let data = ctx.request.body;
    let data2 = await DB.find('user', {"email": data.email});
    let time = sd.format(new Date(), 'YYYY-MM-DD HH:mm');
    if (data2.toString().length > 0){
        let salt = data2[0]["salt"];
        let password = cryptPwd(data.password, salt);
        if (password === data2[0]["password"]) {
            ctx.body = {
                "userId": data2[0]["_id"],
                "username": data2[0]["username"],
                "role": data2[0]["role"],
                "alias": data2[0]["alias"]
            };
            console.log(time + "：查找用户成功" + data2[0]["_id"]);
        } else
            ctx.body = "密码错误";
    } else
        ctx.body = "该邮箱未注册";

}).post("/getUser", async (ctx) => {
    let data = await DB.find('user', DB.getObjectId(ctx.request.body['_id']));
    ctx.body = data;
    let time = sd.format(new Date(), 'YYYY-MM-DD HH:mm');
    if(data.toString().length > 0)
        console.log(time + "：查找用户成功" + data[0]["_id"]);
    else
        console.log(time + "：查找用户失败" + ctx.request.body['_id']);

}).post("/updateUser", async (ctx) => {
    let data = ctx.request.body;
    let time = sd.format(new Date(), 'YYYY-MM-DD HH:mm');
    data._id = DB.getObjectId(data._id);
    let data2 = await DB.update('user', {"_id": data._id}, data);
    if (data2.result.ok){
        ctx.body = 1;
        console.log(time + "：修改用户成功" + data._id);
    } else {
        ctx.body = 0;
        console.log(time + "：修改用户失败" + data._id);
    }

}).get("/getProfilePhoto", async (ctx) => {
    console.log(ctx.body)
    let data;
    let filename = ctx.query["sex"] + ".jpg";
    if (ctx.query["sex"] === "male")
        data = await DB.downloadFile(DB.getObjectId("6052c0fb0e4d4d41090b6cd5"), '/tmp/male.jpg');
    else
        data = await DB.downloadFile(DB.getObjectId("6052c15d59186a4126677e4e"), '/tmp/female.jpg');
    if (data !== 1){
        ctx.body = 0;
    } else {
        const readfilePromise = new Promise((resolve, reject) => {
            fs.readFile('/tmp/'+filename, function(err, data){
                if (err)
                    return reject(err);
                resolve(data)
            })
        });
        await readfilePromise.then(data => ctx.body = data, err => console.log(err));
    }

});

function getRandomSalt() {
    return Math.random().toString().slice(2,5);
}

function cryptPwd(password, salt) {     //密码加密
    let saltPassword = password + ":" + salt;
    let md5 = crypto.createHash('md5');
    return md5.update(saltPassword).digest('hex');
}

module.exports = router.routes();
